package com.party.mobile.web.controller.route;

import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.dao.read.member.PartnerMemberReadDao;
import com.party.core.model.commune.CRoute;
import com.party.core.model.commune.CRouteInfo;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.system.RoleEnum;
import com.party.core.service.commune.ICRouteInfoService;
import com.party.core.service.commune.ICRouteService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.service.system.ISysRoleService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.member.MemberGroupBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.member.output.MemberRouteOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 路线控制器
 *
 * @Date: 2019/10/29 9:08
 */
@RestController
@RequestMapping("route")
public class CRouteController {

    protected static Logger logger = LoggerFactory.getLogger(CRouteController.class);

    @Autowired
    private ICRouteInfoService routeInfoService;

    @Autowired
    private ICRouteService routeService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private PartnerMemberReadDao partnerMemberReadDao;

    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private MemberGroupBizService memberGroupBizService;
    @Autowired
    private ISysRoleService sysRoleService;

    /***
     * 获取机构下的所有路线列表
     * @Date 9:11 2019/10/29
     * @return
     **/
    @Authorization
    @RequestMapping("list")
    public AjaxResult getAllRouteList(HttpServletRequest request) {

        try {
            List<CRoute> routeList = routeService.getAllRoute(memberGroupBizService.getXzgsMemberId(), null);
            return AjaxResult.success(routeList);
        } catch (Exception e) {
            logger.error("获取路线列表失败", e);
            return AjaxResult.error(100, "获取路线列表失败");
        }
    }

    /***
     * 获取路线分析列表
     * @Date 10:48 2019/10/29
     * @param routeId   路线id
     * @param addressType 0：公司地址 1：家地址
     * @param travelType 0：公交 1：驾车
     * @param page
     * @param request
     * @return
     **/
    @Authorization
    @RequestMapping("routeInfo/list")
    public AjaxResult getRouteInfoList(String routeId, Integer addressType, Integer travelType, String memberGroupId, Page page, HttpServletRequest request) {
        if (StringUtils.isEmpty(routeId) || null == routeId) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数为空");
        }
        try {

            Map<String, Object> params = new HashMap<>();
            params.put("routeId", routeId);
            params.put("travelType", travelType);
            params.put("addressType", addressType);

            List<String> orgIds = new ArrayList<>();
            if (StringUtils.isEmpty(memberGroupId)) {
                MemberGroup memberGroup = memberGroupService.get(currentUserBizService.getCurrentUser(request).getId());
                boolean isXzgsAdmin = sysRoleService.hasRole(memberGroup.getId(), RoleEnum.XZGS_ADMIN.getCode());
                if(isXzgsAdmin || StringUtils.isEmpty(memberGroup.getPartnerId())){
                    memberGroupId =memberGroupBizService.getXzgsMemberId();
                    orgIds = memberGroupService.getChildWithMy(memberGroupId);
                }else{
                    orgIds.add(memberGroup.getId());
                }
            }else{
                orgIds.add(memberGroupId);
            }
            params.put("orgIds", orgIds);
            params.put("rFlag", 0);//起点
            //路线分析列表
            List<CRouteInfo> cRouteInfoList = routeInfoService.routeInfoMobileList(params, page);
            List<MemberRouteOutput> outputList = LangUtils.transform(cRouteInfoList, input ->
            {
                Map<String, Object> params1 = new HashMap<>();
                MemberRouteOutput output = new MemberRouteOutput();
                try {
                    com.party.core.utils.MyBeanUtils.copyBeanNotNull2Bean(input, output);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                params1.put("routeId", routeId);
                params1.put("memberId", input.getMemberId());
                params1.put("rFlag", 1);//终点
                params1.put("travelType", input.getTravelType());
                params1.put("addressType", input.getAddressType());
                CRouteInfo routeInfo = routeInfoService.getRouteInfoOne(params1);
                if (null != routeInfo) {
                    output.setEndDistance(routeInfo.getDistance());
                    output.setEndDuration(routeInfo.getDuration());
                    output.setEndStatus(routeInfo.getStatus());
                    output.setEndMessage(routeInfo.getMessage());
                }
                return output;
            });

            return AjaxResult.success(outputList, page);

        } catch (Exception e) {
            logger.error("获取路线分析列表失败", e);
            return AjaxResult.error(100, "获取路线分析列表失败");
        }
    }

    @Authorization
    @RequestMapping("address/list")
    public AjaxResult getAddressList(HttpServletRequest request) {
        try {
            String partnerId = currentUserBizService.getCurrentUser(request).getId();
            List<String> orgIds = memberGroupService.getChildWithMy(partnerId);
            //获取公司地址经纬度
            List<Map<String, Object>> companyAddress = partnerMemberReadDao.companyAddressListMobile(null, orgIds);

            for (Map<String, Object> comAddress : companyAddress) {
                String realname = (String) comAddress.get("realname");
                String title = (String) comAddress.get("title");
                String name = realname + ": " + title;
                comAddress.put("title", name);
            }

            //获取家地址经纬度
            List<Map<String, Object>> homeAddress = partnerMemberReadDao.homeAddressListMobile(null, orgIds);

            for (Map<String, Object> hoAddress : homeAddress) {
                String realname1 = (String) hoAddress.get("realname");
                String title1 = (String) hoAddress.get("title");
                String name1 = realname1 + ": " + title1;
                hoAddress.put("title", name1);
            }

            Map<String, Object> map = new HashMap<>();

            map.put("companyAddressList", companyAddress);
            map.put("homeAddressList", homeAddress);
            return AjaxResult.success(map);

        } catch (Exception e) {
            logger.error("获取地址列表失败", e);
            return AjaxResult.error(100, "获取地址列表失败");
        }
    }

    @Authorization
    @RequestMapping("routeInfo/avg/distance/time")
    public AjaxResult getAvgDistanceAndAvgTime(String routeId, Integer addressType, Integer travelType,String memberGroupId, HttpServletRequest request) {
        if (StringUtils.isEmpty(routeId) || null == routeId) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数为空");
        }
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("routeId", routeId);
            params.put("travelType", travelType);
            params.put("addressType", addressType);

            List<String> orgIds = new ArrayList<>();
            if (StringUtils.isEmpty(memberGroupId)) {
                MemberGroup memberGroup = memberGroupService.get(currentUserBizService.getCurrentUser(request).getId());
                boolean isXzgsAdmin = sysRoleService.hasRole(memberGroup.getId(), RoleEnum.XZGS_ADMIN.getCode());
                if(isXzgsAdmin || StringUtils.isEmpty(memberGroup.getPartnerId())){
                    memberGroupId =memberGroupBizService.getXzgsMemberId();
                    orgIds = memberGroupService.getChildWithMy(memberGroupId);
                }else{
                    orgIds.add(memberGroup.getId());
                }
            }else{
                orgIds.add(memberGroupId);
            }
            params.put("orgIds", orgIds);

            //家、公司到起点的平均时间和路程
            params.put("rFlag", 0);
            Map<String, Object> timeAndDistanceMapStart = routeInfoService.avgDistanceAndTime(params);
            Double avgDistanceStart = 0d;
            Double avgTimeStart = 0d;
            if (null != timeAndDistanceMapStart) {
                avgDistanceStart = (Double) timeAndDistanceMapStart.get("avgDistance");
                avgTimeStart = (Double) timeAndDistanceMapStart.get("avgTime");
            }

            //终点到家、公司的平均时间和路程
            params.put("rFlag", 1);
            Map<String, Object> timeAndDistanceMapEnd = routeInfoService.avgDistanceAndTime(params);
            Double avgDistanceEnd = 0d;
            Double avgTimeEnd = 0d;
            if (null != timeAndDistanceMapEnd) {
                avgDistanceEnd = (Double) timeAndDistanceMapEnd.get("avgDistance");
                avgTimeEnd = (Double) timeAndDistanceMapEnd.get("avgTime");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("avgDistanceStart", avgDistanceStart);
            map.put("avgTimeStart", avgTimeStart);
            map.put("avgDistanceEnd", avgDistanceEnd);
            map.put("avgTimeEnd", avgTimeEnd);
            return AjaxResult.success(map);

        } catch (Exception e) {
            logger.error("获取路线平均路线和时间失败", e);
            return AjaxResult.error(100, "获取路线平均路线和时间失败");
        }
    }

}
